package thread.alternate_print;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-02 16:43
 **/
public class BlockingQueueDemo {

    private final int threadCount;
    private volatile AtomicInteger count = new AtomicInteger(1);
    private final int MAX = 100;
    private final BlockingQueue<Integer>[] queues;

    @SuppressWarnings("unchecked")
    public BlockingQueueDemo(int threadCount) {
        this.threadCount = threadCount;

        this.queues = new ArrayBlockingQueue[threadCount];
        for (int i = 0; i < threadCount; i++) {
            queues[i] = new ArrayBlockingQueue<>(1);
        }
    }

    public void print(int threadIndex) {
        try {
            while (count.get() < MAX) {
                Integer task = queues[threadIndex].take(); // take() 方法如果获取不到任务，就会阻塞
                if (task < 0) return;
                System.out.println(Thread.currentThread().getName() + "-" + task);
                count.incrementAndGet();
                int nextIndex = (threadIndex + 1) % threadCount;
                if (count.get() <= MAX) {
                    queues[nextIndex].put(count.get());
                } else {
                    queues[nextIndex].put(-1);
                }
            }
        } catch (InterruptedException e) {
            return;
        }
    }

//    public void print_1(int threadIndex) {
//        try {
//            while (count < MAX) {
//                Integer task = queues[threadIndex].take();
//                if (task < 0) return;
//                System.out.println(Thread.currentThread().getName() + "-" + task);
//                count++;
//
//                int nextIndex = (threadIndex + 1) % threadCount;
//                if (count <= MAX) {
//                    queues[nextIndex].put(count);
//                } else {
//                    queues[nextIndex].put(-1);
//                }
//            }
//        } catch (InterruptedException e) {
//            return;
//        }
//    }

    public static void main(String[] args) {
        int threadCount = 3;
        BlockingQueueDemo printer = new BlockingQueueDemo(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadIndex = i;
            new Thread(() -> printer.print(threadIndex), "t" + (i + 1)).start();
        }

        try {
            printer.queues[0].put(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
